<template>
  <div class="mainContain">
    <p style="text-align: center;margin-bottom: 20px;padding: 0 30px">
      <el-input
          type="text"
          placeholder="请输入标题"
          v-model="Article.title"
          maxlength="20"
          style="width: 40%;font-size: 30px;height: 60px;"
      />
    </p>
    <v-md-editor v-model="Article.text"
                 height="500px"
                 autofocus="true"
                 :disabled-menus="[]"
                 left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code | save | customToolbar"
                 @save="SaveLocal"
                 :toolbar="toolbar"
                 @upload-image="handleUploadImage" />
    <div style="text-align: center;margin-top: 10px">
      <el-input
          type="textarea"
          rows="4"
          placeholder="请输入文章概述"
          v-model="Article.label"
          style="width: 300px;float: left;margin-bottom: 20px;padding-bottom: 20px"
      />

      <el-select v-model="Article.kind" filterable placeholder="请选择分类">
        <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.name">
        </el-option>
      </el-select>
      <span class="btn sub" @click="updateArticle" v-if="$route.query.id||Article.id!==null">提交修改</span>
      <span class="btn sub" @click="submit" v-else>文章发布</span>
      <span class="btn sub" @click="clearLocalArticle">清空本地</span>
    </div>
  </div>
</template>

<script>
import {articleById, articlePost, updateById} from "@/api/article"
import {imageLoad,imageUploadArticle} from "@/api/upload"
import {getList} from "@/api/kind";

export default {
  name: "editF",
  data(){
    this.toolbar={
      customToolbar: {
        title: '缩进',
            icon: 'v-md-icon-tip',
            action(editor) {
          editor.insert(()=>{
            return {
              text: `&emsp;&emsp;`
            }
          });
        },
      },
    };
    return{
      Article:{
        id:null,
        title:'',
        text:'',
        author:null,
        label:'',
        time:null,
        read:null,
        kind:null
      },
      Init:{
        id:null,
        title:'',
        text:'',
        author:null,
        label:'',
        time:null,
        read:null,
        kind:null
      },
      options: []
    }
  },
  methods:{
    submit(){
      this.$confirm('是否发布文章?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let localGetObject = this.localGetObject(this.userObjectName);
        if(!localGetObject) this.$notify.error(this.notifyMsgErr("您尚未登录！"));
        this.Article.author=localGetObject.username;

        if(this.Article.label===''||this.Article.title===''||this.Article.text===''){
          this.$notify.error(this.notifyMsgErr("请不要留空！"));
          return;
        }

        articlePost(this.Article).then(res=>{

          let d=res.data;
          this.$notify.success(this.notifyMsgSuc(d.data));

          if(d.code==="100"){

            let ids = this.localGetObject(this.articleSaveImageIds);
            if(ids) imageUploadArticle(d.data,ids).then(resp=>{

              let im=resp.data;
              if(im.code==="100"){
                localStorage.removeItem(this.articleSaveImageIds);
                this.$notify.success(this.notifyMsgSuc("图片从属关系已更新！"));

              }else this.$notify.error(this.notifyMsgErr(im.msg))

            }).catch(err=>this.$notify.error(err.message))

            this.Article=this.Init;
            localStorage.removeItem(this.articleEditTemplate);//清空本地文章编辑存储

            this.$router.push('/index');

          }else this.$notify.error(this.notifyMsgErr(d.msg));

        }).catch(err=>this.$notify.error(this.notifyMsgErr(err.message)));

        this.$message({
          type: 'success',
          message: '执行成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消发布！'
        });
      });
    },
    SaveLocal(){
      this.localSetObject(this.articleEditTemplate,this.Article);
      this.$notify.success(this.notifyMsgSuc('保存到本地！'));
    },
    handleUploadImage(event, insertImage, files){

      let file=new FormData();
      file.append('file',files[0]);

      imageLoad(file).then(res=>{
        let data = res.data;

        if(data.code==="100"){
          this.$notify.success(this.notifyMsgSuc("图片插入成功！"));
          insertImage({
            url:data.data[0],
            desc:files.name
          });
          let ids=this.localGetObject(this.articleSaveImageIds);
          if(!ids) {
            ids=[data.data[1]];
          }else ids.push(data.data[1]);

          this.localSetObject(this.articleSaveImageIds,ids);

        }
      }).catch(err=>this.$notify.error(this.notifyMsgErr(err.message)));
    },
    updateArticle(){
      // updateById(this.Article).then(res=>{
      //
      //   let result = res.data;
      //
      //   if(result.code==="100") this.$notify.success(this.notifyMsgSuc(result.data));
      //   else this.$notify.error(this.notifyMsgErr(result.data));
      //
      // }).catch(err=>this.$notify.error(this.notifyMsgErr(err.message)));

      this.$confirm('是否更新文章?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let localGetObject = this.localGetObject(this.userObjectName);
        if(!localGetObject) this.$notify.error(this.notifyMsgErr("您尚未登录！"));
        this.Article.author=localGetObject.username;

        if(this.Article.label===''||this.Article.title===''||this.Article.text===''){
          this.$notify.error(this.notifyMsgErr("请不要留空！"));
          return;
        }

        updateById(this.Article).then(res=>{

          let d=res.data;
          this.$notify.success(this.notifyMsgSuc(d.data));

          if(d.code==="100"){

            let ids = this.localGetObject(this.articleSaveImageIds);
            if(ids) imageUploadArticle(this.Article.id,ids).then(resp=>{

              let im=resp.data;

              if(im.code==="100"){

                localStorage.removeItem(this.articleSaveImageIds);

                this.$notify.success(this.notifyMsgSuc("图片从属关系已更新！"));

              }else this.$notify.error(this.notifyMsgErr(im.msg));

            }).catch(err=>this.$notify.error(err.message));

            this.Article=this.Init;
            localStorage.removeItem(this.articleEditTemplate);//清空本地文章编辑存储

            this.$router.push('/index');

          }else this.$notify.error(this.notifyMsgErr(d.msg));

        }).catch(err=>this.$notify.error(this.notifyMsgErr(err.message)));

        this.$message({
          type: 'success',
          message: '执行成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消发布！'
        });
      });
    },
    clearLocalArticle(){

      this.$confirm('是否清空?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem(this.articleEditTemplate);
        this.Article=this.Init;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    }
  },
  mounted() {

    let id = this.$route.query.id;

    if(id) {

      articleById(id).then(res=>{

        let data = res.data;

        if(data.code==="100") this.Article=data.data;
        else this.$notify.error(this.notifyMsgErr(data.msg))

      }).catch(err=>this.$notify.error(this.notifyMsgErr(err.message)))

    }

    getList().then(res=>{
      if(res.data.code==="100")this.options=res.data.data;
      else this.$notify.error(this.notifyMsgErr(res.data.msg));
    }).catch(err=>this.$notify.error(this.notifyMsgErr(err.message)));

    let local=this.localGetObject(this.articleEditTemplate);

    if(local) this.Article=local;

  },
  beforeRouteLeave(){
    this.SaveLocal();
  }
}
</script>

<style scoped>
  .mainContain{
    margin-bottom: 100px;
  }
  .sub{
    float: right;
    padding: 5px;
  }
</style>
